<template>
  <el-tree-select
    v-loading="loading"
    style="width: 100%"
    :data="calculateOptions"
    node-key="label"
    :props="treeProps"
    :render-after-expand="false"
    :placeholder="placeholder"
    @visible-change="visibleChange"
    check-strictly
    filterable
    clearable
    :empty-values="[null]"
    :value-on-clear="null"
  >
  </el-tree-select>
</template>
<script setup name="YTreeSelect">
const loading = ref(false);
const dynamicOptions = ref();

const props = defineProps({
  /* 配置项 */
  treeProps: {
    type: Object,
    default: () => {
      return {
        value: "id", // ID字段名
        label: "name", // 显示名称
        children: "children", // 子级字段名
      };
    },
  },
  options: { type: Array, default: [] },
  placeholder: { type: String, default: "请选择" },
  optionsFunc: { type: Function, default: undefined },
  optionsParams: { type: Object, default: { nopaginate: true } },
});

const calculateOptions = computed(() => {
  return dynamicOptions.value ? dynamicOptions.value : props.options;
});

/** 获取选项列表 */
function visibleChange(val) {
  if (props.optionsFunc) {
    if (val) {
      loading.value = true;
      props.optionsFunc(props.optionsParams).then((response) => {
        dynamicOptions.value = response.data;
        loading.value = false;
      });
    }
  }
}
</script>
